/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: MainActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.main.ui;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatButton;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.bhex.app.R;
import io.bhex.app.account.event.LocaleChangeEvent;
import io.bhex.app.account.ui.MyAssetFragment;
import io.bhex.app.app.APPConfig;
import io.bhex.app.app.SkinManager;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.kline.ui.KlineTestActivity;
import io.bhex.app.main.manager.RefreshLayoutManager;
import io.bhex.app.main.presenter.MainPresenter;
import io.bhex.app.market.bean.FavoriteRecordBean;
import io.bhex.app.market.ui.MarketFragment;
import io.bhex.app.trade.ui.ContractTradeFragment;
import io.bhex.app.trade.ui.HomeTradeFragment;
import io.bhex.app.utils.BasicFunctionsUtil;
import io.bhex.app.utils.CoinUtils;
import io.bhex.app.utils.FingerTipUtil;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.VersionUpdateUtil;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.BhexSdk;
import io.bhex.sdk.PhoneUtil;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.app.AppStatusConstant;
import io.bhex.sdk.config.bean.BasicFunctionsConfig;
import io.bhex.sdk.data_manager.RateAndLocalManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.FavoriteListResponse;

/**
 * ================================================
 * 描   述：主屏
 * ================================================
 */
public class MainActivity extends BaseActivity<MainPresenter, MainPresenter.MainUI> implements MainPresenter.MainUI, View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    private AppCompatButton btn_click;

    private static KeyBackListener mKeyBackListener;
    private int[] tabResIdArr = {
            R.id.main_home_tab,
            R.id.main_market_tab,
            R.id.main_trade_tab,
            R.id.main_contract_trade_tab,
            R.id.main_asset
    };
    private int curCheckedId = Integer.MAX_VALUE;
    private View myStatusBar;
    private CoinPairBean currentPairBean;
    private MarketFragment mMarketFragment;
    private HomeTradeFragment mTradeFragment;
    private ContractTradeFragment mContractTradeFragment;
    private MyAssetFragment myAssetFragment;

    private FingerTipUtil mFingerTip;

    private static final int REQUEST_ASSET_Login = 101;
    public static MainActivity mMainActivity;

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    protected MainPresenter.MainUI getUI() {
        return this;
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_main;
    }


    public static MainActivity getInstance() {
        return mMainActivity;
    }

//    //沉浸式状态栏颜色
//    @Override
//    public int getColorPrimary() {
//        return R.color.color_f8f8f8;
//    }

    @Override
    protected boolean translucentStatusBar() {
        return true;
    }

    private RadioGroup bottomTab;

    @Override
    protected void restartApp() {
//        super.restartApp();
//        Toast.makeText(getApplicationContext(),"应用被回收重启",Toast.LENGTH_LONG).show();
        startActivity(new Intent(this, SplashActivity.class));
        finish();
    }



    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int action = intent.getIntExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_BACK_TO_HOME);
        switch (action) {
            case AppStatusConstant.ACTION_RESTART_APP:
                restartApp();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //换肤
        //SkinManager.getInstance().initConfig();
        PhoneUtil.getInstance().initDevice(this);


        super.onCreate(savedInstanceState);

        if(savedInstanceState!=null){
            getPresenter().hiddenFragment();
        }

        EventBus.getDefault().register(this);

        initFragment();
        BhexSdk.Start();

        VersionUpdateUtil.checkVersionUpdate(this, true);

        //默认跳转到 HomeFragment
        //if (savedInstanceState == null)
            setTabChecked(R.id.main_home_tab);

        if (getIntent() != null)
            getPresenter().handleIntent(getIntent());

        mMainActivity = this;

    }

    @Override
    protected void onResume() {
        super.onResume();
        RefreshLayoutManager.initLocalize(this);
        DebugLog.d("RefreshLayoutManager","REFRESH_HEADER_PULLING=="+getString(R.string.bh_srl_header_pulling));

        /*boolean isSkinBlackMode = SPEx.get(AppData.SPKEY.SKIN_IS_BLACK_MODE, false);
        myStatusBar.setBackgroundColor(isSkinBlackMode ? getResources().getColor(R.color.color_bg_2_night) : getResources().getColor(R.color.color_bg_2));
        if (isSkinBlackMode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //实现状态栏图标和文字颜色为浅色
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, 0);
            }

        }else{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //实现状态栏图标和文字颜色为暗色
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                getWindow().getDecorView().findViewById(android.R.id.content).setPadding(0, 0, 0, 0);
            }

        }*/

        SymbolDataManager.GetInstance().setLoginChangeObserver(new SymbolDataManager.LoginstatusChange() {
            @Override
            public void onFavriateChange() {
                //TODO 暂不同步服务端收藏
//                HashMap<String,CoinPairBean> localFavoriteMap = new HashMap<>();
//
//                FavoriteRecordBean favorite = KlineUtils.getFavorite();
//                List<CoinPairBean> favoriteList = new ArrayList<>();
//                if (favorite != null) {
//                    if (favorite.getData() != null) {
//                        favoriteList = favorite.getData();
//                    }
//                    if (favoriteList != null && favoriteList.size()>0) {
//                        for (CoinPairBean coinPairBean : favoriteList) {
//                            localFavoriteMap.put(coinPairBean.getSymbolId(),coinPairBean);
//                        }
//                    }
//                }
//
//                //默认都取config接口symbol(全量列表)的实体列表
//                HashMap<String, CoinPairBean> bbSymbolMap = SymbolDataManager.GetInstance().getBBSymbolMap();
//
//                //登录添加网络同步的自选，
//                if (UserInfo.isLogin()) {
//                    //如果登录了，先清空本地和内存中的自选
//                    Map<String, FavoriteListResponse.FavoriteBean> loginFavoritesMap = SymbolDataManager.GetInstance().getFavoritesMap();
//                    for (String key : loginFavoritesMap.keySet()) {
//                        FavoriteListResponse.FavoriteBean favoriteBean = loginFavoritesMap.get(key);
//                        String favoriteSymbolId = favoriteBean.getSymbolId();
//                        if (!localFavoriteMap.containsKey(favoriteSymbolId)) {
//                            CoinPairBean coinPairBean = bbSymbolMap.get(favoriteSymbolId);
//                            coinPairBean.setFavorite(true);
//                            if (coinPairBean != null) {
//                                favoriteList.add(0,coinPairBean);
//                            }
//                        }
//                    }
//
//                    KlineUtils.saveFavorite(favoriteList);
//                }

            }
        });

    }

    @Override
    protected void initView() {
        super.initView();
        bottomTab = viewFinder.find(R.id.main_tab);
        BasicFunctionsConfig basicFunctionsConfig = BasicFunctionsUtil.getBasicFunctionsConfig();

        bottomTab.findViewById(R.id.main_trade_tab).setVisibility(basicFunctionsConfig.isExchange() && basicFunctionsConfig.isOtc() ? View.GONE : View.VISIBLE);

        bottomTab.findViewById(R.id.main_contract_trade_tab).setVisibility(basicFunctionsConfig.isOption() && basicFunctionsConfig.isFuture() ? View.GONE : View.VISIBLE);

//        myStatusBar = viewFinder.find(R.id.myStatusBar);
//        ViewGroup.LayoutParams layoutParamsStatus = myStatusBar.getLayoutParams();
//        layoutParamsStatus.height = PixelUtils.getStatusBarHeight(this);
//        myStatusBar.setLayoutParams(layoutParamsStatus);

        //指纹设置提示弹框
        if (!SPEx.isFingerOpen() && !SPEx.isFingerTip() && UserInfo.isLogin()) {
            mFingerTip = new FingerTipUtil(this, new FingerTipUtil.OnFingerFinish() {
                @Override
                public void OnFingerFinish() {
                    SPEx.setFingerTip(true);
                }
            });
            mFingerTip.showFingerDialog();
        }

    }

    private HashMap<String, Fragment> mainFragments = new HashMap<>();
    private void initFragment() {
        HomeFragment homeFragment = new HomeFragment();
        MarketFragment marketFragment = new MarketFragment();
        HomeTradeFragment tradeFragment = new HomeTradeFragment();
        ContractTradeFragment contractTradeFragment = new ContractTradeFragment();
        MyAssetFragment assetFragment = new MyAssetFragment();

        mainFragments.put(HomeFragment.class.getName(),homeFragment);
        mainFragments.put(MarketFragment.class.getName(),marketFragment);
        mainFragments.put(HomeTradeFragment.class.getName(),tradeFragment);
        mainFragments.put(ContractTradeFragment.class.getName(),contractTradeFragment);
        mainFragments.put(MyAssetFragment.class.getName(),assetFragment);

    }

    @Override
    public HashMap<String, Fragment> getMainFragments() {
        return mainFragments;
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        //
        RateAndLocalManager.GetInstance(this).initRateKind(this);
        APPConfig.getInstance().initZendesk();
        ((RadioGroup) viewFinder.find(R.id.main_tab)).setOnCheckedChangeListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BhexSdk.Stop();
        DebugLog.d("[MainActivity]","===onDestroy==");
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CoinPairBean coinPairBean) {
        //去交易
        if (coinPairBean == null )
            return;
        currentPairBean = coinPairBean;
        if (coinPairBean.isNeedSwitchTradeTab()) {
            if (KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())) {
                CoinUtils.saveOptionTradeCoin(coinPairBean);
                goOptionTrade();
            } else if (KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())) {
                CoinUtils.saveContractTradeCoin(coinPairBean);
                goFuturesTrade();
            } else if (KlineUtils.isSymbolOfBB(coinPairBean.getCoinType())) {
                CoinUtils.saveBBTradeCoin(coinPairBean);
                goBBTrade();
                //startActivity(new Intent(this, KlineTestActivity.class));
            }

        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("position",curCheckedId);
        super.onSaveInstanceState(outState);

    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        if (intent != null) {
//            /*currentPairBean = (CoinPairBean) intent.getSerializableExtra(AppData.INTENT.SYMBOLS);
//            int tab = intent.getIntExtra(AppData.INTENT.MAIN_TAB, 0);
//            setTabChecked(2);
//            if(tab == 2) {
//                int tradeTab = intent.getIntExtra(AppData.INTENT.HOME_TRADE_TAB, 0);
//                if(mTradeFragment != null)
//                    mTradeFragment.SetTab(tradeTab);
//            }*/
////            setTabChecked(tab);
//        }
//    }

    /**
     * 行情列表
     */
    public void goMarket() {
        setTabChecked(R.id.main_market_tab);
    }

    public void goBBTrade() {
        setTabChecked(R.id.main_trade_tab);
        if (mTradeFragment != null)
            mTradeFragment.SetTab(HomeTradeFragment.TAB_TRADE);
    }

    public void goOTCTrade() {
        setTabChecked(R.id.main_trade_tab);
        if (mTradeFragment != null)
            mTradeFragment.SetTab(HomeTradeFragment.TAB_OTC);
    }

    public void goOptionTrade() {
        setTabChecked(R.id.main_contract_trade_tab);
        if (mContractTradeFragment != null)
            mContractTradeFragment.SetTab(ContractTradeFragment.TAB_OPTION);
    }

    public void goFuturesTrade() {
        setTabChecked(R.id.main_contract_trade_tab);
        if (mContractTradeFragment != null)
            mContractTradeFragment.SetTab(ContractTradeFragment.TAB_FUTURES);
    }

    public void goAsset() {
        setTabChecked(R.id.main_asset);
        if (myAssetFragment != null)
            myAssetFragment.SetTab(MyAssetFragment.TAB_WALLET);
    }

    public void goOptionAsset() {
        setTabChecked(R.id.main_asset);
        if (myAssetFragment != null)
            myAssetFragment.SetTab(MyAssetFragment.TAB_OPTION);
    }

    public void goCoinPlusAsset() {
        setTabChecked(R.id.main_asset);
        if (myAssetFragment != null)
            myAssetFragment.SetTab(MyAssetFragment.TAB_FINANCE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    private String STATUS_BAR_PROPERTY_NAME = "statusBar";

    public void rotateyAnimRun(final View view, float start, float end) {
        ObjectAnimator anim = ObjectAnimator
                .ofFloat(view, STATUS_BAR_PROPERTY_NAME, start, end)
                .setDuration(200);
        anim.start();
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cVal = (Float) animation.getAnimatedValue();
                view.setAlpha(cVal);
//                view.setScaleX(cVal);
                view.setScaleY(cVal);
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, final int checkedId) {

        if (curCheckedId == checkedId) {
            return;
        }
        //DebugLog.d("MainActivity==>:","=d=abc=="+checkedId);

        switch (checkedId) {
            case R.id.main_home_tab:
                getPresenter().showFragment(mainFragments.get(HomeFragment.class.getName()), null);
                break;
            case R.id.main_market_tab:

                mMarketFragment = (MarketFragment) getPresenter().showFragment(mainFragments.get(MarketFragment.class.getName()), null);
                break;
            case R.id.main_trade_tab: {
                Bundle bundle = new Bundle();
                bundle.putSerializable(AppData.INTENT.SYMBOLS, currentPairBean);
                mTradeFragment = (HomeTradeFragment) getPresenter().showFragment(mainFragments.get(HomeTradeFragment.class.getName()), bundle);
                break;
            }
            case R.id.main_contract_trade_tab: {
                Bundle bundle = new Bundle();
                bundle.putSerializable(AppData.INTENT.SYMBOLS, currentPairBean);
                mContractTradeFragment = (ContractTradeFragment) getPresenter().showFragment(mainFragments.get(ContractTradeFragment.class.getName()), bundle);
                break;
            }
            case R.id.main_asset: {
                if (UserInfo.LoginAndGoin(MainActivity.this, AppData.INTENT.LOGIN_CALLER_MAIN, REQUEST_ASSET_Login) == true) {

                    myAssetFragment = (MyAssetFragment) getPresenter().showFragment(mainFragments.get(MyAssetFragment.class.getName()), null);
                    break;
                } else {
                    bottomTab.check(curCheckedId);
                    return;
                }
            }

        }

        curCheckedId = checkedId;

    }


//    @Override
//    public void onCheckedChanged(RadioGroup group, final int checkedId) {
//
//        if (curCheckedId == checkedId) {
//            return;
//        }
//
//        switch (checkedId) {
//            case R.id.main_home_tab:
//                getPresenter().showFragment(HomeFragment.class, null);
//                break;
//            case R.id.main_market_tab:
//
//                mMarketFragment = (MarketFragment) getPresenter().showFragment(MarketFragment.class, null);
//                break;
//            case R.id.main_trade_tab: {
//                Bundle bundle = new Bundle();
//                bundle.putSerializable(AppData.INTENT.SYMBOLS, currentPairBean);
//                mTradeFragment = (HomeTradeFragment) getPresenter().showFragment(HomeTradeFragment.class, bundle);
//                break;
//            }
//            case R.id.main_contract_trade_tab: {
//                Bundle bundle = new Bundle();
//                bundle.putSerializable(AppData.INTENT.SYMBOLS, currentPairBean);
//                mContractTradeFragment = (ContractTradeFragment) getPresenter().showFragment(ContractTradeFragment.class, bundle);
//                break;
//            }
//            case R.id.main_asset: {
//                if (UserInfo.LoginAndGoin(MainActivity.this, AppData.INTENT.LOGIN_CALLER_MAIN, REQUEST_ASSET_Login) == true) {
//
//                    myAssetFragment = (MyAssetFragment) getPresenter().showFragment(MyAssetFragment.class, null);
//                    break;
//                } else {
//                    bottomTab.check(curCheckedId);
//                    return;
//                }
//            }
//
//        }
//
//        curCheckedId = checkedId;
//
////        changeStatusBar(checkedId);
//
//
//    }

    /**
     * 改变自定义状态栏状态
     *
     * @param checkedId
     */
    private void changeStatusBar(int checkedId) {
        //兼容系统 19以下无透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            if (checkedId == R.id.main_home_tab) {
                //首页不显示
                //rotateyAnimRun(myStatusBar, 1.0f, 0.0f);
                myStatusBar.setVisibility(View.GONE);
            } else {
                myStatusBar.setVisibility(View.GONE);
                //rotateyAnimRun(myStatusBar, 0.0f, 1.0f);
            }
        } else {
            //兼容系统
            myStatusBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void setTabChecked(int tabResId) {
        bottomTab.check(tabResId);
//        bottomTab.check(tabResIdArr[index]);
    }

    @Override
    public int getTabCheckedIndex() {
        for (int i = 0; i < tabResIdArr.length; i++)
            if (tabResIdArr[i] == curCheckedId)
                return i;

        return -1;
    }

    @Override
    public View getBottomView() {
        return viewFinder.find(R.id.main_tab);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent msg) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mKeyBackListener != null) {
                mKeyBackListener.onKeyBack();
                return true;
            }
        }

        boolean result = getPresenter().handleKeyUp(keyCode, msg);
        if (!result)
            return super.onKeyUp(keyCode, msg);
        else
            return result;
    }

    /**
     * 注册返回键监听
     *
     * @param keyBackListener
     */
    public static void registerBackKeyListener(KeyBackListener keyBackListener) {
        mKeyBackListener = keyBackListener;
    }

    /**
     * 移除返回键监听
     */
    public static void removeBackKeyListener() {
        mKeyBackListener = null;
    }

    public interface KeyBackListener {
        void onKeyBack();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mFingerTip != null)
            mFingerTip.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ASSET_Login && resultCode == RESULT_OK) {
            myAssetFragment = (MyAssetFragment) getPresenter().showFragment(mainFragments.get(MyAssetFragment.class.getName()), null);
            setTabChecked(R.id.main_asset);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeLanguage(LocaleChangeEvent changeEvent){
        misNeedRomve = 0;
        //recreate();
    }

}
